package com.hsylient.javase.chapter11.practice;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
 * 使用多线程下载图片
 *
 * 使用commons-io包
 * 每次下载完成以后，都会打印对应下载文件的名字。观察多次打印的结束，发现执行的顺序其实是不相同的，说明是并行执行，不是顺序执行
 */
public class DownloadPicture extends Thread {

    private String url;
    private String fileName;

    public DownloadPicture(String url, String fileName) {
        this.url = url;
        this.fileName = fileName;
    }

    public static void main(String[] args) throws IOException {
        new DownloadPicture("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg5q.duitang.com%2Fuploads%2Fitem%2F201505%2F04%2F20150504183354_zLZjV.jpeg&refer=http%3A%2F%2Fimg5q.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667094188&t=29522f0e453e5dbca6c622e5d1a06ab1",
                "1.jpg").start();
        new DownloadPicture("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F201810%2F05%2F20181005203850_cAAYa.thumb.1000_0.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667095053&t=da87498d6c2100fb0e7487aea27f9a5a",
                "2.jpg").start();
        new DownloadPicture("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F201910%2F23%2F20191023212200_kQraP.thumb.1000_0.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667095053&t=974710337c136d1ed8a25d05bb60f0a1",
                "3.jpg").start();

    }

    @Override
    public void run() {
        downPicture();
    }

    public void downPicture() {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(fileName));
            System.out.println("下载文件的名称为：" + fileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
